#include "session.h"
#include "common.h"
#include <QUuid>
#include <QDebug>
#include <QString>
#include <QDateTime>

// 会话类型到字符串的映射
QString sessionTypeToString(SessionType type) {
    switch (type) {
    case SessionType::HTTP:
        return "HTTP";
    case SessionType::HTTPS:
        return "HTTPS";
    case SessionType::DNS:
        return "DNS";
    case SessionType::FTP:
        return "FTP";
    case SessionType::SSH:
        return "SSH";
    case SessionType::SMTP:
        return "SMTP";
    case SessionType::POP3:
        return "POP3";
    case SessionType::IMAP:
        return "IMAP";
    default:
        return "Other";
    }
}

// ProtocolSession构造函数
ProtocolSession::ProtocolSession() {
    id = QUuid::createUuid().toString();
    type = SessionType::OTHER;
    typeString = "Other";
    state = SessionState::ACTIVE;
    startTime = QDateTime::currentDateTime();
    clientAddress = "";
    serverAddress = "";
    clientPort = 0;
    serverPort = 0;
    totalBytes = 0;
    requestCount = 0;
    responseCount = 0;
    summary = "";
}

// ProtocolSession析构函数
ProtocolSession::~ProtocolSession() {
    packetIndices.clear();
    additionalInfo.clear();
}

// 添加数据包到会话
void ProtocolSession::addPacket(int packetIndex) {
    if (!packetIndices.contains(packetIndex)) {
        packetIndices.append(packetIndex);
    }
}

// 更新会话状态
void ProtocolSession::updateState(SessionState newState) {
    if (state != newState) {
        state = newState;
        if (state == SessionState::COMPLETED || 
            state == SessionState::ERROR || 
            state == SessionState::TIMED_OUT) {
            endTime = QDateTime::currentDateTime();
        }
    }
}

// 计算会话持续时间
qint64 ProtocolSession::getDurationMs() const {
    if (endTime.isValid()) {
        return startTime.msecsTo(endTime);
    }
    return startTime.msecsTo(QDateTime::currentDateTime());
}

// 获取会话的可读摘要
QString ProtocolSession::getReadableSummary() const {
    QString durationStr;
    qint64 durationMs = getDurationMs();
    
    if (durationMs < 1000) {
        durationStr = QString("%1 ms").arg(durationMs);
    } else {
        durationStr = QString("%1 s").arg(durationMs / 1000.0, 0, 'f', 1);
    }
    
    QString stateStr;
    switch (state) {
    case SessionState::ACTIVE:
        stateStr = "活跃";
        break;
    case SessionState::COMPLETED:
        stateStr = "已完成";
        break;
    case SessionState::ERROR:
        stateStr = "错误";
        break;
    case SessionState::TIMED_OUT:
        stateStr = "超时";
        break;
    }
    
    return QString("%1 会话 [%2] - %3:%4 <-> %5:%6 (%7 数据包, %8 字节, %9, %10)")
            .arg(typeString)
            .arg(stateStr)
            .arg(clientAddress)
            .arg(clientPort)
            .arg(serverAddress)
            .arg(serverPort)
            .arg(packetIndices.size())
            .arg(totalBytes)
            .arg(summary.isEmpty() ? "无摘要" : summary)
            .arg(durationStr);
}